﻿using Storage.DbEntities.Base;
using Storage.Repositories.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Storage.Accessors.Base
{
	public abstract class BaseAccessor<TEntity, TDbEntity>
		where TDbEntity : BaseDbEntity, new()
		where TEntity : Domain.Base.BaseEntity
	{
		private BaseRep<TDbEntity> _rep;

		public BaseAccessor(BaseRep<TDbEntity> rep)
		{
			_rep = rep;
		}

		public async Task<IEnumerable<TEntity>> GetAllActivitiesAsync()
		{
			var dbRes = await _rep.GetAll();
			return dbRes.Select(FromDbEntity).ToList();
		}

		public abstract TEntity FromDbEntity(TDbEntity dbEntity);

		public async Task InsertAllAsync(IEnumerable<TEntity> entities)
		{
			foreach (var entity in entities)
			{
				await InsertAsync(entity);
			}
		}

		public async Task InsertAsync(TEntity entity)
		{
			var dbEntity = ToDbEntity(entity);
			await _rep.InsertAsync(dbEntity);
		}

		public abstract TDbEntity ToDbEntity(TEntity entity);

		public virtual async Task<TEntity> GetByIdAsync(Guid id)
		{
			var dbRes = await _rep.GetByIdAsync(id);
			return FromDbEntity(dbRes);
		}

		public abstract Task<TDbEntity> Find(TEntity entity);
	}
}
